package com.inventory.controller;

import com.inventory.service.ProductService;
import com.inventory.service.PurchaseRecordService;
import com.inventory.service.SaleRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;

@Controller
public class DashboardController {

    @Autowired
    private ProductService productService;
    
    @Autowired
    private PurchaseRecordService purchaseRecordService;
    
    @Autowired
    private SaleRecordService saleRecordService;

    @GetMapping({"/", "/dashboard"})
    public String dashboard(Model model, Authentication authentication) {
        // 获取当前月份的开始和结束时间
        LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endOfMonth = LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        
        // 获取本月销售总额
        Double monthlySales = saleRecordService.getTotalSaleAmount(startOfMonth, endOfMonth);
        model.addAttribute("monthlySales", monthlySales);
        
        // 获取本月利润
        Double monthlyProfit = saleRecordService.getTotalProfit(startOfMonth, endOfMonth);
        model.addAttribute("monthlyProfit", monthlyProfit);
        
        // 获取本月进货总额
        Double monthlyPurchases = purchaseRecordService.getTotalPurchaseAmount(startOfMonth, endOfMonth);
        model.addAttribute("monthlyPurchases", monthlyPurchases);
        
        // 获取库存不足的商品
        model.addAttribute("lowStockProducts", productService.findLowStockProducts());
        
        // 获取热销商品
        model.addAttribute("topSellingProducts", saleRecordService.findTopSellingProducts(startOfMonth, endOfMonth, 5));
        
        return "dashboard";
    }
} 